//
//  HDRequestObj.m
//  HDBeiJingYanQiHu
//
//  Created by 牛的mini on 7/19/16.
//  Copyright © 2016 牛的mini. All rights reserved.
//

#import "HDRequestObj.h"
#import "LCCoolHUD.h"

@interface HDRequestObj()
{
    HDDeclare *declare;
}
@property (nonatomic, strong) JQIndicatorView *myIndicator;
@property (nonatomic, strong) UIView *myLoginCoverView;

@end

@implementation HDRequestObj

- (id)init
{
    self = [super init];
    if (self)
    {}
    declare = [HDDeclare sharedDeclare];
    return self;
}

#pragma mark
#pragma mark -------- Request Methods --------

// 只是上传字符串
- (void)requestPath:(NSString *)path
          Parameter:(NSDictionary *)parametersDic
             withVC:(UIViewController *)vcTemp
{
    [self showRequestIndicator:vcTemp];
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.requestSerializer.timeoutInterval = 3.0f;
    //session.responseSerializer = [AFHTTPResponseSerializer serializer]; // 返回非标准JSON格式时候加这一句
    
    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html",@"text/json",@"text/javascript", nil];
    [session POST:path parameters:parametersDic progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *loginDic = responseObject;
        [self cleanRequestIndicator];
        if (vcTemp != nil)
            self.myDataBlock(loginDic);
        //LOG(@"Resonse is %@", loginDic);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self cleanRequestIndicator];
        [LCCoolHUD showFailure:declare.connectFailed zoom:NO shadow:NO];
        NSLog(@"request error is %@", error);
    }];
}

- (void)requestPath:(NSString *)path
          Parameter:(NSDictionary *)parametersDic
             withVC:(UIViewController *)vcTemp
            timeout:(CGFloat)timeout
{
    [self showRequestIndicator:vcTemp];
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.requestSerializer.timeoutInterval = timeout;
    //session.responseSerializer = [AFHTTPResponseSerializer serializer]; // 返回非标准JSON格式时候加这一句
    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html",@"text/json",@"text/javascript", nil];
    [session POST:path parameters:parametersDic progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *loginDic = responseObject;
        [self cleanRequestIndicator];
        if (vcTemp != nil)
            self.myDataBlock(loginDic);
        //LOG(@"Resonse is %@", loginDic);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self cleanRequestIndicator];
        [LCCoolHUD showFailure:declare.connectFailed zoom:NO shadow:NO];
        [[NSNotificationCenter defaultCenter] postNotificationName:kMy_Request_Failed_Notification object:vcTemp];
        NSLog(@"request error is %@", error);
        if (self.failedBlock)
        {self.failedBlock(nil);}
    }];
}

- (void)requestGetPath:(NSString *)path
          Parameter:(NSDictionary *)parametersDic
             withVC:(UIViewController *)vcTemp
            timeout:(CGFloat)timeout
{
    [self showRequestIndicator:vcTemp];
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.requestSerializer.timeoutInterval = timeout;
    //session.responseSerializer = [AFHTTPResponseSerializer serializer]; // 返回非标准JSON格式时候加这一句
    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html",@"text/json",@"text/javascript", nil];
    [session GET:path parameters:parametersDic progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *loginDic = responseObject;
        [self cleanRequestIndicator];
        if (vcTemp != nil)
            self.myDataBlock(loginDic);
        //LOG(@"Resonse is %@", loginDic);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self cleanRequestIndicator];
        [LCCoolHUD showFailure:declare.connectFailed zoom:NO shadow:NO];
        [[NSNotificationCenter defaultCenter] postNotificationName:kMy_Request_Failed_Notification object:vcTemp];
        NSLog(@"request error is %@", error);
        if (self.failedBlock)
        {self.failedBlock(nil);}
    }];
}

// 请求更新资源
- (void)requestPath:(NSString *)path
       md5Parameter:(NSDictionary *)jsonDic
{
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.requestSerializer.timeoutInterval = 10;
    //session.responseSerializer = [AFHTTPResponseSerializer serializer]; // 返回非标准JSON格式时候加这一句
    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html",@"text/json",@"text/javascript", nil];
//    session.requestSerializer = [AFJSONRequestSerializer serializer]; // 声明使用json请求
    
    [session POST:path parameters:jsonDic progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *loginDic = responseObject;
        self.myDataBlock(loginDic);
        //LOG(@"Resonse is %@", loginDic);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        LOG(@"request error is %@", error);
        if (self.failedBlock)
        {self.failedBlock(nil);}
    }];
}

// 需要上传NSData
- (void)requestPath:(NSString *)path
          Parameter:(NSDictionary *)parametersDic
             withVC:(UIViewController *)vcTemp
            dataDic:(NSDictionary *)imgDataDic
{
    [self showRequestIndicator:vcTemp];
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.requestSerializer.timeoutInterval = 5.0f;

    //session.responseSerializer = [AFHTTPResponseSerializer serializer]; // 返回非标准JSON格式时候加这一句
    
    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html",@"text/json",@"text/javascript", nil];
    [session POST:path parameters:parametersDic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        // 上传文件
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat            = @"yyyyMMddHHmmss";
        NSString *str                    = [formatter stringFromDate:[NSDate date]];
        NSString *fileName               = [NSString stringWithFormat:@"%@.png", str];
        
        NSData *imageData = imgDataDic[@"img"];
        [formData appendPartWithFileData:imageData name:@"img" fileName:fileName mimeType:@"image/png"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *loginDic = responseObject;
        [self cleanRequestIndicator];
        //if (vcTemp != nil)
            self.myDataBlock(loginDic);
        //LOG(@"Resonse is %@", loginDic);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self cleanRequestIndicator];
        [LCCoolHUD showFailure:declare.connectFailed zoom:NO shadow:NO];
        self.myDataBlock(nil);

        NSLog(@"request error is %@", error);
    }];
}

// 需要上传NSData
- (void)requestPath:(NSString *)path
          Parameter:(NSDictionary *)parametersDic
             withVC:(UIViewController *)vcTemp
          dataArray:(NSArray *)imgDataArray
{
    [self showRequestIndicator:vcTemp];
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.requestSerializer.timeoutInterval = 6.0f;
    
    //session.responseSerializer = [AFHTTPResponseSerializer serializer]; // 返回非标准JSON格式时候加这一句
    
    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html",@"text/json",@"text/javascript", nil];
    [session POST:path parameters:parametersDic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        // 上传文件
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat            = @"yyyyMMddHHmmss";
        
        for (NSInteger i=0;i<imgDataArray.count;i++)
        {
            NSString *str                    = [formatter stringFromDate:[NSDate date]];
            NSString *fileName               = [NSString stringWithFormat:@"%@.png", str];
            
            NSData *imageData = imgDataArray[i];
            [formData appendPartWithFileData:imageData name:@"img" fileName:fileName mimeType:@"image/png"];
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *loginDic = responseObject;
        [self cleanRequestIndicator];
        if (vcTemp != nil)
            self.myDataBlock(loginDic);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self cleanRequestIndicator];
        [LCCoolHUD showFailure:declare.get_failed zoom:NO shadow:NO];
        NSLog(@"request error is %@", error);
    }];
}

- (void)requestPath:(NSString *)path
          Parameter:(NSDictionary *)parametersDic
{
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.requestSerializer.timeoutInterval = 6.0f;
    //session.responseSerializer = [AFHTTPResponseSerializer serializer]; // 返回非标准JSON格式时候加这一句
    
    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html",@"text/json",@"text/javascript", nil];
    [session POST:path parameters:parametersDic progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *loginDic = responseObject;
        self.myDataBlock(loginDic);
        //LOG(@"Resonse is %@", loginDic);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"request error is %@", error);
        //[LCCoolHUD showFailure:declare.connectFailed zoom:NO shadow:NO];
    }];
}


- (void)requestGet:(NSString *)path
          Parameter:(NSDictionary *)parametersDic
{
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.requestSerializer.timeoutInterval = 6.0f;
    //session.responseSerializer = [AFHTTPResponseSerializer serializer]; // 返回非标准JSON格式时候加这一句
    
    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html",@"text/json",@"text/javascript", nil];
    [session GET:path parameters:parametersDic progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *loginDic = responseObject;
        self.myDataBlock(loginDic);
        //LOG(@"Resonse is %@", loginDic);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"request error is %@", error);
        //[LCCoolHUD showFailure:declare.connectFailed zoom:NO shadow:NO];
    }];
}

#pragma mark
#pragma mark ------- Tip UIs --------

- (void)cleanRequestIndicator
{
    [_myIndicator stopAnimating];
    [_myIndicator removeFromSuperview];
    self.myIndicator = nil;
    
    [_myLoginCoverView removeFromSuperview];
    self.myLoginCoverView = nil;
}

- (void)showRequestIndicator:(UIViewController *)requestVC
{
    if (requestVC == nil)
        return;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        _myLoginCoverView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, requestVC.view.frame.size.width, requestVC.view.frame.size.height)];
        _myLoginCoverView.backgroundColor = [UIColor colorWithWhite:0.5 alpha:0.6];
        [requestVC.view addSubview:_myLoginCoverView];
        
        _myIndicator = [[JQIndicatorView alloc] initWithType:2];
        _myIndicator.center = requestVC.view.center;
        [_myLoginCoverView addSubview:_myIndicator];
        [_myIndicator startAnimating];
    });
}

- (void)showTipIndicator:(UIViewController *)tipVC
                 Success:(BOOL)succ
                TipWords:(NSString *)tipWords
{
    if(succ == YES)
        [LCCoolHUD showSuccessOblong:tipWords inView:tipVC.view zoom:YES shadow:NO];
    else
        [LCCoolHUD showFailure:tipWords zoom:NO shadow:NO];
}

@end
